package com.simpleim.starter.client;

import com.simpleim.im.common.bean.User;
import com.simpleim.im.common.bean.msg.ProtoMsg;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

import java.util.HashMap;
import java.util.Map;

public class ClientSession {
    private User user;

    private Channel channel;

    private String sessionId;

    private boolean isConnected = false;

    private boolean isLogin = false;

    public static final AttributeKey<ClientSession> KEY_SESSION = AttributeKey.newInstance("key_session");

    /**
     * session中存储的session 变量属性值
     */
    private Map<String, Object> map = new HashMap<String, Object>();

    public ClientSession(Channel channel) {
        this.channel = channel;
        this.sessionId = String.valueOf(-1);
        this.channel.attr(KEY_SESSION).set(this);
    }

    public static void closeSession(Channel channel) {
        channel.close();
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void setConnected(boolean connected) {
        isConnected = connected;
    }

    public void setLogin(boolean login) {
        isLogin = login;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public String getSessionId() {
        return sessionId;
    }

    public boolean isConnected() {
        return isConnected;
    }

    public boolean isLogin() {
        return isLogin;
    }

    public Channel getChannel() {
        return channel;
    }

    /**
     * 登录成功
     * @param ctx
     * @param msg
     */
    public static void loginSuccess(ChannelHandlerContext ctx, ProtoMsg.Message msg) {
        ClientSession session = ctx.attr(KEY_SESSION).get();
        if (session != null) {
            session.setLogin(true);
            session.setSessionId(msg.getSessionId());
        }
    }

    public static ClientSession getSession(ChannelHandlerContext ctx) {
        final Channel channel = ctx.channel();
        return channel.attr(KEY_SESSION).get();
    }

//    public static void logout(ChannelHandlerContext ctx) {
//        ClientSession session = ctx.attr(KEY_SESSION).get();
//        if (session != null) {
//
//        }
//    }
}
